package com.hdu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hdu.entity.Music;
import com.hdu.mapper.MusicMapper;
import com.hdu.pojo.PageBean;
import com.hdu.pojo.Sort;
import com.hdu.service.IMusicService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdu.vo.Cartoon;
import lombok.RequiredArgsConstructor;
import net.dongliu.requests.Requests;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * <p>
 * 歌曲实体类 服务实现类
 * </p>
 *
 * @author xiaobai
 * @since 2025-02-07
 */
@Service
@RequiredArgsConstructor
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music> implements IMusicService {

    private final MusicMapper musicMapper;

    private final String ComicsUrl = "https://www.qctcu.com/";

    /**
     * 网站链接查询
     */
    @Override
    public PageBean<Music> page(Integer current, Integer size, String name) {
        Page<Music> page = new Page<>(current, size);

        IPage<Music> iPage = this.page(page);

        return new PageBean<>(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 热门歌曲查询
     */
    @Override
    public List<Music> hotMusic() {
        QueryWrapper<Music> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("count").last("limit 10");
        return musicMapper.selectList(wrapper);
    }

    /**
     * 增加歌曲次数
     */
    @Override
    public void addCount(String id) {
        UpdateWrapper<Music> wrapper = new UpdateWrapper<>();
        wrapper.setSql("count = count + 1").eq("id", id);
        musicMapper.update(null, wrapper);
    }

//    @Override
//    public List<Song> searchMusic(String name, String page) {
//
//        String url = "https://music.liuzhijin.cn/";
//
//        Map<String, Object> headers = new HashMap<>();
//        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36");
//        headers.put("x-requested-with", "XMLHttpRequest");
//
//        HashMap<String, Object> param = new HashMap<>();
//        param.put("input", name);
//        param.put("filter", "name");
//        param.put("type", "netease");
//        param.put("page", page);
//
//        MusicCode musicCode = Requests.post(url).headers(headers).body(param).send().readToJson(MusicCode.class);
//        return musicCode.getData();
//    }

    @Override
    public PageBean<Cartoon> searchCartoon(String name, String page) throws IOException {


        PageBean<Cartoon> pageBean = new PageBean<>();
        String url = "https://yinghua.ee/so" + name + "/page/" + page + ".html";

        Document doc = Jsoup.parse(new URL(url), 20000);


        Elements cartoons = doc.select(".stui-vodlist__media li");
        pageBean.setTotal((long) cartoons.size());

        List<Cartoon> cartoonList = new ArrayList<>();
        for (Element element : cartoons) {
            Cartoon cartoon = new Cartoon();
            String cover = element.getElementsByTag("a").attr("data-original");
            if (!cover.contains("https")) {
                cover = "https://yinghua.ee" + cover;
            }
            cartoon.setCover(cover);
            String str = element.getElementsByTag("a").attr("href");
            cartoon.setId(str.substring(str.lastIndexOf("/") + 1));
            cartoon.setTitle(element.getElementsByTag("a").attr("title"));
            cartoon.setText(element.getElementsByClass("pic-text").text());
            cartoonList.add(cartoon);
        }
        Elements list = doc.select(".stui-page li");

        if (list.size() != 0) {
            String str = Objects.requireNonNull(list.last()).getElementsByTag("a").attr("href");
            pageBean.setTotal((long) Integer.parseInt(str.substring(str.lastIndexOf("/") + 1, str.lastIndexOf("."))));
        }
        pageBean.setRows(cartoonList);
        return pageBean;
    }

    @Override
    public List<Cartoon> searchComics(String name) throws IOException {

        List<Cartoon> cartoonList = new ArrayList<>();
        String url = ComicsUrl + "search?key=" + name;


        Document doc = Jsoup.parse(new URL(url), 20000);
        Elements elements = doc.select(".bookList_3 .item");

        for (Element element : elements) {
            Cartoon cartoon = new Cartoon();
            cartoon.setId(element.getElementsByTag("a").attr("href").replaceAll("/", ""));
            cartoon.setCover(element.getElementsByTag("img").attr("data-src"));
            cartoon.setTitle(element.getElementsByTag("p").get(0).text());
            cartoon.setText(element.getElementsByTag("p").get(1).text());
            cartoonList.add(cartoon);
        }
        return cartoonList;
    }


    @Override
    public Cartoon detailCartoon(String id) throws IOException {

        Cartoon cartoon = new Cartoon();
        cartoon.setId(id);
        String url = "https://yinghua.ee/video/" + id;


        Document doc = Jsoup.parse(new URL(url), 20000);

        cartoon.setText(doc.select(".pic-text").get(0).text());
        cartoon.setTitle(doc.select(".stui-content__detail .title").text());
        cartoon.setContent(doc.select(".detail-content").text().replace("详情", ""));

        Elements elements = doc.select(".stui-content__detail .data");
        cartoon.setActor(elements.get(0).text().substring(3).replaceAll("[^\\u4e00-\\u9fa5]", " ").split(" "));
        cartoon.setDirector(elements.get(1).text().substring(3).replaceAll("[^\\u4e00-\\u9fa5]", " ").split(" "));
        String[] combine = elements.get(2).text().split(" ");
        cartoon.setType(combine[0].substring(3));
        cartoon.setRegion(combine[1].substring(3));
        cartoon.setYear(combine[2].substring(3));
        cartoon.setTime(elements.get(3).text().substring(3));

        String cover = doc.select(".stui-vodlist__thumb img").attr("data-original");
        if (!cover.contains("https")) {
            cover = "https://yinghua.ee" + cover;
        }
        cartoon.setCover(cover);

        List<Sort> chapterList = new ArrayList<>();
        for (Element element : doc.select(".stui-content__playlist").get(0).select("a")) {
            Sort sort = new Sort();
            sort.setLabel(element.text());
            sort.setPath(element.attr("href").substring(element.attr("href").lastIndexOf("/") + 1));
            chapterList.add(sort);
        }
        cartoon.setChapterList(chapterList);
        return cartoon;
    }

    @Override
    public Cartoon detailComics(String id) throws IOException {

        Cartoon cartoon = new Cartoon();
        cartoon.setId(id);
        String url = ComicsUrl + id + "/";


        Document doc = Jsoup.parse(new URL(url), 20000);

        cartoon.setCover(doc.select(".banner_detail_form img").attr("src"));
        cartoon.setTitle(doc.select(".banner_detail_form .info h1").text());

        Elements elements = doc.select(".banner_detail_form .info p");
        cartoon.setDirector(new String[]{elements.get(0).text().substring(3)});
        String[] combine = elements.get(1).text().split(" ");
        cartoon.setType(combine[1].substring(3));
        cartoon.setRegion(combine[0].substring(3));
        cartoon.setTime(combine[2].substring(5));
        cartoon.setContent(elements.get(3).text().substring(5));

        List<Sort> chapterList = new ArrayList<>();
        for (Element element : doc.select(".view-win-list").get(0).select("a")) {
            Sort sort = new Sort();
            sort.setLabel(element.text());
            sort.setPath(element.attr("href").substring(element.attr("href").lastIndexOf("/") + 1));
            chapterList.add(sort);
        }
        cartoon.setChapterList(chapterList);

        url = "http://www.kumwu1.com/chapterlist/" + id + "/";

        Map<String, Object> headers = new HashMap<>();
        headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36");
        headers.put("x-requested-with", "XMLHttpRequest");

        String str = Requests.get(url).headers(headers).send().readToText();
        JSONArray jsonArray = JSONObject.parseObject(str).getJSONObject("data").getJSONArray("list");

        for (Object object : jsonArray) {
            Sort sort = new Sort();
            sort.setLabel((String) ((JSONObject) object).get("name"));
            sort.setPath(((JSONObject) object).get("id") + ".html");
            chapterList.add(sort);
        }

        return cartoon;
    }

    @Override
    public String videoPath(String id) throws IOException {

        String url = "https://yinghua.ee/play/" + id;

        Document doc = Jsoup.parse(new URL(url), 20000);

        String str = doc.select(".stui-player__video script").get(0).data();

        String json = str.substring(str.indexOf("{"), str.lastIndexOf("}") + 1);

        JSONObject jsonObject = JSONObject.parseObject(json);

        return jsonObject.getString("url");
    }

    @Override
    public List<String> comicsPath(String id, String comicsId) throws IOException {

        List<String> comicsData = new ArrayList<>();

        String url = ComicsUrl + comicsId + "/" + id;

        Document doc = Jsoup.parse(new URL(url), 20000);

        comicsData.add(doc.select(".readerContainer").attr("data-id"));

        String str = doc.select("body script").get(0).toString().split("\n")[1].trim();
        comicsData.add(str.replace("return p", "__c0rst96=p.substring(14).replaceAll('\"','')"));

        comicsData.add(doc.select(".chaptitle a").attr("href"));
        comicsData.add(doc.select(".chaptitle a").attr("title"));
        comicsData.add(doc.select(".chaptitle h1").text());
        comicsData.add(doc.select(".imgFloat a").get(0).attr("href"));
        comicsData.add(doc.select(".imgFloat a").get(1).attr("href"));

        return comicsData;
    }
}
